#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<pthread.h>
#include <unistd.h>
#define PORT 8888
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024

int clients[MAX_CLIENTS]={0};

void broadcast(int fd,const char*msg){
   for(size_t i=0;i<MAX_CLIENTS;i++){
if(clients[i]!=0){  
    send(clients[i],msg,strlen(msg),0);

}
}
}




void *handle_client(void*argc){
    
int client_fd=*(int*)argc;
char buffer[BUFFER_SIZE]={0};
while(1){
    int len=read(client_fd,buffer,BUFFER_SIZE);
    if(len<=0){
        close(client_fd);
        break;
    }
    buffer[len]='\0';
    broadcast(client_fd,buffer);
    printf("收到客户端%d的信息%s\n",client_fd,buffer);
    memset(buffer,0,sizeof(buffer));
}
for(size_t i=0;i<MAX_CLIENTS;i++){
    if(clients[i]==client_fd){
        clients[i]=0;
        break;
    }
}
free(argc);
pthread_exit(NULL);
}


int main(){

int server_fd,new_socket;

socket(AF_INET,SOCK_STREAM,0);
//socket
if(server_fd==-1)
{
    perror("socket create failed\n");
    exit(EXIT_FAILURE);
}

struct sockaddr_in address;
address.sin_family=AF_INET;//ipv4
address.sin_addr.s_addr=INADDR_ANY;
address.sin_port=htons(PORT);
//2 bind
int rc=bind(server_fd,(struct sockaddr*)&address,sizeof(address));
if(rc<0){
    perror("bind error!\n");
    exit(EXIT_FAILURE);
}
//3 listen
rc=listen(server_fd,3);
if(rc<0){
    perror("listen error!\n");
    exit(EXIT_FAILURE);
}
//4 accept
socklen_t addrlen=sizeof(address);
perror("wait client connect......\n");
while(1){
    new_socket=accpet(server_fd,(struct sockaddr*)&address,&addrlen);


if(new_socket<0){
    perror("accept error!\n");
    continue;
}

for(size_t i=0;i<MAX_CLIENTS;i++)
{
if(clients[i]=0)
{
    clients[i]=new_socket;
    break;
}
}


pthread_t thread_id;
int *client_fd_ptr=malloc(sizeof(int));
*client_fd_ptr=new_socket;
pthread_create(&thread_id,NULL,handle_client,client_fd_ptr);


}
perror("*******************\n");
return 0;
}